#include "fakecharger.h"
#include "canmessage.h"
#include <QDebug>

static const quint32 CHARGER_STATUS_IDENTIFIER = 0x18FF5000;
static const quint32 CHARGER_COMMAND_IDENTIFIER = 0x180600F4;

FakeCharger::FakeCharger(SerialPortManager &portManager, QObject *parent) :
    QObject(parent)
  , PortManager(portManager)
  , MessageSendTimer()
  , SourceAddress(CHARGER_SA)
  , ChargeComplete(false)
  , MasterState(false)
{
    connect(&MessageSendTimer, SIGNAL(timeout()), this, SLOT(SendMessage()));
    MessageSendTimer.setInterval(1000);
    connect(&MasterSendTimer, SIGNAL(timeout()), this, SLOT(SendMaster()));
    MasterSendTimer.setInterval(100);
    MasterSendTimer.setSingleShot(true);
}

void FakeCharger::SendMessage()
{
    QVector<quint8> data;
    if(ChargeComplete)
    {
        qDebug() <<"Acting like charge is done";
        data.push_back(0x7F);
        data.push_back(0x00);
        data.push_back(0x00);
        data.push_back(0x00);
    }
    else
    {
        data.push_back(0x09);
        data.push_back(0x02);
        data.push_back(0x10);
        data.push_back(0x10);
    }
    data.push_back(0x00);
    data.push_back(0x00);
    data.push_back(0x00);
    data.push_back(0x00);
    CanMessage mess(CHARGER_STATUS_IDENTIFIER | SourceAddress, data);
    PortManager.SendLine(mess.GetAsSnifferSendString());

    if(MasterState)
    {
        MasterSendTimer.start();
        CanMessage masterMessage(CHARGER_COMMAND_IDENTIFIER | (SourceAddress << 8), data);
        PortManager.SendLine(masterMessage.GetAsSnifferSendString());
    }
}

void FakeCharger::SendMaster()
{
    QVector<quint8> data;
    if(ChargeComplete)
    {
        qDebug() <<"Acting like charge is done";
        data.push_back(0x7F);
        data.push_back(0x00);
        data.push_back(0x00);
        data.push_back(0x00);
    }
    else
    {
        data.push_back(0x09);
        data.push_back(0x02);
        data.push_back(0x10);
        data.push_back(0x10);
    }
    data.push_back(0x00);
    data.push_back(0x00);
    data.push_back(0x00);
    data.push_back(0x00);

}

void FakeCharger::setState(bool state)
{
    if(state)
    {
        StartSending();
    }
    else
    {
        StopSending();
    }
}

void FakeCharger::setMasterState(bool state)
{
    MasterState = state;
}

void FakeCharger::setChargeComplete(bool complete)
{
    ChargeComplete = complete;
}

void FakeCharger::StartSending()
{
    MessageSendTimer.start();
    SendMessage();
}

void FakeCharger::StopSending()
{
    MessageSendTimer.stop();
}
